import { Card, Button, Checkbox, Form, Input, message } from 'antd'
import logo from '../../assets/logo.png'
import './index.scss'
import { useDispatch } from 'react-redux'
import { loginAction } from '@/store/modules/login'
import { useNavigate } from 'react-router-dom'

const Login = () => {
  const dis = useDispatch()
  const nav = useNavigate()
  const onFinish = async (values) => {

    // console.log('Success:', values)
    try {

      await dis(loginAction(values))
      message.success('登陆成功')
      nav('/')
    } catch (error) {
      console.log(error)
      message.error(error.reponse.data.message)
    }
  }

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo)
  }
  const validCode = (_, value) => {
    return value ? Promise.resolve() : Promise.reject(new Error('请勾选同意协议'))
  }
  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        {/* form.item里面rules的触发条件必须是form里面的子集 validateTrigger*/}
        <Form validateTrigger={['onBlur', 'onChange']}
          initialValues={{
            // 表单变量初始化
            mobile: '13911111111',
            code: '246810',
            agree: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          {/* 手机号 */}
          <Form.Item
            // 定义表单变量叫啥
            name="mobile"
            rules={[
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur'
              },
              { required: true, message: '请输入手机号' }
            ]}
          >
            <Input size="large" placeholder='请输入手机号' />
          </Form.Item>
          {/* 验证码 */}
          <Form.Item
            name="code"
            rules={[
              { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
              { required: true, message: '请输入验证码' }
            ]}
          >
            {/* <Input.Password /> */}
            <Input size="large" placeholder='请输入验证码' maxLength={6} />
          </Form.Item>
          {/* 手机号验证码这边,form.item 包裹的是input, */}
          {/* 同意协议 */}
          <Form.Item
            name="agree"
            rules={[{ validator: validCode }]}
            valuePropName="checked"
          >
            <Checkbox>我已阅读并同意用户协议和隐私条款</Checkbox>
          </Form.Item>

          <Form.Item
          >
            {/* 要进行一个提交操作,则必须要htmlType="submit" */}
            <Button type="primary" htmlType="submit" block size='large'>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div >
  )
}

export default Login